package common.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import java.net.URI;
import java.util.Map;

public class SpringHttpUtil {
    public static SimpleClientHttpRequestFactory _httpRequestFactory = new SimpleClientHttpRequestFactory();

    public static ClientHttpResponse Get(String url, Map<String, String> headers) throws Exception {
        URI uri = new URI(url);
        ClientHttpRequest httpRequest = _httpRequestFactory.createRequest(uri, HttpMethod.GET);
        System.out.println("Http get " + uri);

        HttpHeaders httpHeaders = httpRequest.getHeaders();
        for (Map.Entry<String, String> header : headers.entrySet())
            httpHeaders.set(header.getKey(), header.getValue());

        ClientHttpResponse httpResponse = httpRequest.execute();
        System.out.println("Response Code " + httpResponse.getStatusCode());

        System.out.println();
        return httpResponse;
    }

    public static void Download(String url, String path, Map<String, String> headers) throws Exception {
        try {
            URI uri = new URI(url);
            System.out.println("Downloading " + uri);
            ClientHttpRequest httpRequest = _httpRequestFactory.createRequest(uri, HttpMethod.GET);

            HttpHeaders httpHeaders = httpRequest.getHeaders();
            for (Map.Entry<String, String> header : headers.entrySet())
                httpHeaders.set(header.getKey(), header.getValue());

            ClientHttpResponse httpResponse = httpRequest.execute();
            System.out.println("Response Code " + httpResponse.getStatusCode());

            System.out.println("Try to save to " + path);
            FileUtil.save(path, httpResponse.getBody());
            httpResponse.close();

            System.out.println();
        } catch (Exception ex) {
            LogUtil.record(ex);
        }
    }

    public static String PostJson(String url, String json) throws Exception {
        URI uri = new URI(url);
        ClientHttpRequest httpRequest = _httpRequestFactory.createRequest(uri, HttpMethod.POST);

        HttpHeaders httpHeaders = httpRequest.getHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        BinaryUtil.WriteText(httpRequest.getBody(), json, CharsetUtil.Utf8);

        ClientHttpResponse httpResponse = httpRequest.execute();
        return BinaryUtil.getText(httpResponse.getBody());
    }
}
